import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class _36_有效的数独 {
    @Test
    public void test(){
        char [][]arr={{'5','3','.','.','7','.','.','.','.'},
                      {'6','.','.','1','9','5','.','.','.'},
                      {'.','9','8','.','.','.','.','6','.'},
                      {'8','.','.','.','6','.','.','.','3'},
                      {'4','.','.','8','.','3','.','.','1'},
                      {'7','.','.','.','2','.','.','.','6'},
                      {'.','6','.','.','.','.','2','8','.'},
                      {'.','.','.','4','1','9','.','.','5'},
                      {'.','.','.','.','8','.','.','7','9'}};
        System.out.println(isValidSudoku(arr));
    }

    /**
     * 先判断行是否满足，在判断列是否满足，在判断格子是否满足
     * @param board
     * @return
     */
    public boolean isValidSudoku(char[][] board) {

        for (int i = 0; i < board.length; i++) {
            int tempRow=0;
            int tempLine=0;
            Set<Character> row =new HashSet<>();
            Set<Character> line =new HashSet<>();
            for (int j = 0; j < board.length; j++) {
                //先判断每一行是否符合要求
                if (board[i][j]!='.'){
                    tempRow++;
                    row.add(board[i][j]);
                }
                //先判断每一列是否符合要求
                if (board[j][i]!='.'){
                    tempLine++;
                    line.add(board[j][i]);
                }
            }
            if (tempRow!=row.size()||tempLine!=line.size()){
                return false;
            }


            }
        //在判断每一个格子是否符合要求
        for (int i = 0; i < board.length; i+=3) {

            for (int j = 0; j <board.length; j+=3) {
                int temp=0;
                Set<Character> nums =new HashSet<>();
                for (int k = i; k <i+3 ; k++) {
                    for (int l = j; l < j+3; l++) {
                        if (board[k][l]!='.'){
                            temp++;
                            nums.add(board[k][l]);
                        }
                    }
                }
                if (temp!= nums.size()) return false;
            }

        }
        return true;

        }

}
